package com.rt.tmpt.controller.filter;

import com.rt.tmpt.utils.WebUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.Set;

/**
 * ip filter web.xml configuration method
 * <!-- ip filter -->
 * <filter>
 * <filter-name>systemFilter</filter-name>
 * <filter-class>com.wuxiaoyong.filter.IpFilter</filter-class>
 * <init-param>
 * <param-name>ip1</param-name>
 * <param-value>192.168.200.8</param-value>
 * </init-param>
 * <init-param>
 * <param-name>ip2</param-name>
 * <param-value>192.168.200.9</param-value>
 * </init-param>
 * </filter>
 * <filter-mapping>
 * <filter-name>systemFilter</filter-name>
 * <url-pattern>/*</url-pattern>
 * </filter-mapping>
 *
 * @author pay
 */
public class IpFilter implements Filter {
    private Logger log = LoggerFactory.getLogger(this.getClass());
    private Set<String> allowedIpList = new HashSet<String>();

    public void init(FilterConfig cfg) throws ServletException {
        Enumeration<String> ipEnum = cfg.getInitParameterNames();
        while (ipEnum.hasMoreElements()) {
            String ipKey = ipEnum.nextElement();
            String ip = cfg.getInitParameter(ipKey);
            allowedIpList.add(ip);
        }
    }

    public void doFilter(ServletRequest arg0, ServletResponse arg1,
                         FilterChain arg2) throws IOException, ServletException {

        HttpServletRequest request = (HttpServletRequest) arg0;
        HttpServletResponse response = (HttpServletResponse) arg1;

        String ip = WebUtils.getRealIp(request);// request.getRemoteHost();
        log.debug("ip:" + ip);

        if ("0:0:0:0:0:0:0:1".equals(ip)) { //127.0.0.1访问时，打印的ip是这个
            arg2.doFilter(arg0, arg1);
            return;
        }
        if ("127.0.0.1".equals(ip)) {
            arg2.doFilter(arg0, arg1);
            return;
        }
        if ("127.0.0.1".equals(ip)) {
            arg2.doFilter(arg0, arg1);
            return;
        }
        if (allowedIpList.contains(ip)) {
            arg2.doFilter(arg0, arg1);
            return;
        }

        PrintWriter out = response.getWriter();
        out.print("Illegel access , your ip is not in ip container which allows some ip to access. ");
        out.close();
    }

    public void destroy() {
        allowedIpList = null;
    }

}
